#!/bin/bash
set -euo pipefail

# 配置参数
SERVICE_NAME="uv-fastapi"
PROJECT_DIR="/opt/coc"
LOG_DIR="/var/log/coc"
SERVICE_FILE="$PROJECT_DIR/uv-fastapi.service"
SYSTEMD_SERVICE_FILE="/etc/systemd/system/$SERVICE_NAME.service"
REPO_URL="https://gitee.com/zhuxiaohuaqn/clashofclans.git"

# 错误处理函数
error_exit() {
    echo "ERROR: $1" >&2
    exit 1
}

# 确认提示
confirm() {
    read -p "$1 [y/N] " -n 1 -r
    echo
    [[ $REPLY =~ ^[Yy]$ ]] || error_exit "用户取消操作"
}

# 服务状态检查
check_service_status() {
    if sudo systemctl is-active --quiet "$SERVICE_NAME"; then
        echo "$SERVICE_NAME 服务正在运行"
        return 0
    else
        echo "$SERVICE_NAME 服务未运行"
        return 1
    fi
}

# 安装功能
install() {
    echo "===== 开始安装 $SERVICE_NAME ====="

    # 检查sudo权限
    if ! sudo -v &>/dev/null; then
        error_exit "需要sudo权限，请确保当前用户有sudo访问权限"
    fi

    # 安装必要依赖
    echo "安装基础依赖..."
    if command -v apt &> /dev/null; then
        sudo apt update || error_exit "apt更新失败"
        sudo apt install -y git netcat-openbsd || error_exit "基础依赖安装失败"
    elif command -v yum &> /dev/null; then
        sudo yum install -y git nc || error_exit "基础依赖安装失败"
    elif command -v dnf &> /dev/null; then
        sudo dnf install -y git nc || error_exit "基础依赖安装失败"
    else
        error_exit "无法检测到有效的包管理器，请手动安装git和netcat"
    fi

    # 检测git是否安装
    if ! command -v git &> /dev/null; then
        error_exit "Git安装失败，请检查网络连接"
    fi

    # 检测uv是否安装
    if ! command -v uv &> /dev/null; then
        echo "uv未安装，正在安装..."
        if detect_network_environment; then
            curl -LsSf https://ghproxy.com/https://astral.sh/uv/install.sh | sh || error_exit "uv安装脚本执行失败"
        else
            curl -LsSf https://astral.sh/uv/install.sh | sh || error_exit "uv安装脚本执行失败"
        fi
        
        if ! grep -q "$HOME/.local/bin" <<< "$PATH"; then
            echo "export PATH=\"\\$PATH:\\$HOME/.local/bin\"" >> "$HOME/.bashrc"
            export PATH="\$PATH:\$HOME/.local/bin"
            echo "已将uv路径添加到环境变量"
        fi
    fi

    # 克隆/更新项目
    if [ -d "$PROJECT_DIR/.git" ]; then
        echo "目标目录已存在Git仓库，执行更新操作..."
        cd "$PROJECT_DIR" || error_exit "无法进入项目目录"
        git pull || error_exit "Git拉取更新失败"
    else
        echo "正在克隆项目到$PROJECT_DIR..."
        sudo mkdir -p "$PROJECT_DIR" || error_exit "创建目标目录失败"
        sudo chown -R "$USER":"$USER" "$PROJECT_DIR" || error_exit "设置目录权限失败"
        git clone "$REPO_URL" "$PROJECT_DIR" || error_exit "Git克隆失败"
    fi

    # 进入项目目录并同步依赖
    cd "$PROJECT_DIR" || error_exit "无法进入项目目录"

    if detect_network_environment; then
        configure_domestic_mirrors
    fi

echo "同步项目依赖..."
echo "当前PyPI源: $(uv config get index-url)"
uv sync || error_exit "uv依赖同步失败"

    # 创建日志文件目录
    if [ ! -d "$LOG_DIR" ]; then
        echo "创建日志目录: $LOG_DIR"
        sudo mkdir -p "$LOG_DIR" || error_exit "创建日志目录失败"
        sudo chown -R "$USER":"$USER" "$LOG_DIR" || error_exit "设置日志目录权限失败"
        sudo chmod -R 0755 "$LOG_DIR" || error_exit "设置日志目录权限失败"
    fi

    # 安装服务文件到系统目录
    echo "安装系统服务..."
    sudo cp "$SERVICE_FILE" "$SYSTEMD_SERVICE_FILE" || error_exit "复制服务文件失败"
    sudo systemctl daemon-reload || error_exit "重新加载systemd配置失败"

    # 设置开机自启并启动服务
    echo "设置开机自启..."
    sudo systemctl enable "$SERVICE_NAME" || error_exit "设置开机自启失败"

    echo "启动服务..."
    sudo systemctl start "$SERVICE_NAME" || error_exit "启动服务失败"

    # 验证服务状态
    verify_service_status "$SERVICE_NAME"

    echo -e "\n===== 安装完成 ====="
    echo "服务状态: $(sudo systemctl is-active --quiet "$SERVICE_NAME" && echo "运行中" || echo "已停止")"
    echo "日志目录: $LOG_DIR"
}

# 卸载功能
uninstall() {
    echo "===== 开始卸载 $SERVICE_NAME ====="

    # 停止并禁用服务
    if sudo systemctl is-active --quiet "$SERVICE_NAME"; then
        echo "停止服务..."
        sudo systemctl stop "$SERVICE_NAME" || error_exit "停止服务失败"
    fi

    if sudo systemctl is-enabled --quiet "$SERVICE_NAME"; then
        echo "禁用开机自启..."
        sudo systemctl disable "$SERVICE_NAME" || error_exit "禁用服务失败"
    fi

    # 删除服务文件
    if [ -f "$SYSTEMD_SERVICE_FILE" ]; then
        echo "删除服务文件: $SYSTEMD_SERVICE_FILE"
        sudo rm -f "$SYSTEMD_SERVICE_FILE" || error_exit "删除服务文件失败"
        sudo systemctl daemon-reload || error_exit "重新加载systemd配置失败"
    fi

    # 删除项目文件
    if [ -d "$PROJECT_DIR" ]; then
        confirm "确定要删除项目目录 $PROJECT_DIR 吗？此操作不可恢复！"
        echo "删除项目目录..."
        sudo rm -rf "$PROJECT_DIR" || error_exit "删除项目目录失败"
    fi

    # 删除日志文件
    if [ -d "$LOG_DIR" ]; then
        echo "删除日志目录: $LOG_DIR"
        sudo rm -rf "$LOG_DIR" || error_exit "删除日志目录失败"
    fi

    # 清理git配置（如果之前设置了镜像）
    if git config --global --get url."https://gitee.com/mirrors/".insteadOf >/dev/null; then
        confirm "是否恢复git配置（移除gitee镜像）？"
        git config --global --unset url."https://gitee.com/mirrors/".insteadOf || true
    fi

    echo -e "\n===== 卸载完成 ====="
    echo "已清除以下组件："
    echo "1. 系统服务: $SERVICE_NAME"
    echo "2. 项目文件: $PROJECT_DIR"
    echo "3. 日志文件: $LOG_DIR"
}

# 重载功能
reload() {
    echo "===== 重载 $SERVICE_NAME 配置 ====="
    if [ ! -f "$SYSTEMD_SERVICE_FILE" ]; then
        error_exit "服务文件不存在，请先安装服务"
    fi

    # 复制最新服务文件
    echo "更新服务配置..."
    sudo cp "$SERVICE_FILE" "$SYSTEMD_SERVICE_FILE" || error_exit "复制服务文件失败"
    sudo systemctl daemon-reload || error_exit "重新加载systemd配置失败"

    # 重启服务
    echo "重启服务..."
    sudo systemctl restart "$SERVICE_NAME" || error_exit "重启服务失败"

    # 检查状态
    check_service_status
    echo -e "\n===== 重载完成 ====="
}

# 状态功能
status() {
    echo "===== $SERVICE_NAME 服务状态 ====="
    sudo systemctl status "$SERVICE_NAME" --no-pager
    echo -e "\n服务运行状态: $(check_service_status && echo "正常" || echo "异常")"
    echo -e "日志位置: $LOG_DIR\n"
}

# 重启功能
restart() {
    echo "===== 重启 $SERVICE_NAME ====="
    if ! sudo systemctl is-active --quiet "$SERVICE_NAME"; then
        echo "服务未运行，直接启动..."
        sudo systemctl start "$SERVICE_NAME" || error_exit "启动服务失败"
    else
        echo "重启服务..."
        sudo systemctl restart "$SERVICE_NAME" || error_exit "重启服务失败"
    fi

    # 验证服务状态
    verify_service_status "$SERVICE_NAME"
    echo -e "\n===== 重启完成 ====="
}

# 服务状态验证函数
verify_service_status() {
    local service_name="$1"
    local max_attempts=5
    local attempt=1
    local delay=3

    echo "验证服务状态..."
    while [ $attempt -le $max_attempts ]; do
        if sudo systemctl is-active --quiet "$service_name"; then
            echo "服务$service_name启动成功"
            return 0
        fi

        echo "服务未启动，等待$delay秒后重试（第$attempt/$max_attempts次）"
        sleep $delay
        attempt=$((attempt + 1))
    done

    echo "服务启动验证失败，执行手动检查..."
    echo "1. 服务状态:"
    sudo systemctl status "$service_name" --no-pager
    echo -e "\n2. 最近10条系统日志:"
    sudo journalctl -u "$service_name" -n 10 --no-pager

    error_exit "服务$service_name启动失败，请查看上述日志排查问题"
}

# 网络环境检测函数
detect_network_environment() {
    echo "检测网络环境..."
    local timeout=3
    local domestic_test=(
        "gitee.com:443"
        "mirrors.tuna.tsinghua.edu.cn:443"
        "pypi.tuna.tsinghua.edu.cn:443"
    )
    local foreign_test=(
        "github.com:443"
        "pypi.org:443"
    )

    # 测试国内站点连通性
    local domestic_reachable=0
    for endpoint in "${domestic_test[@]}"; do
        if nc -z -w "$timeout" "${endpoint%%:*}" "${endpoint#*:}"; then
            domestic_reachable=$((domestic_reachable + 1))
        fi
    done

    # 测试国外站点连通性
    local foreign_reachable=0
    for endpoint in "${foreign_test[@]}"; do
        if nc -z -w "$timeout" "${endpoint%%:*}" "${endpoint#*:}"; then
            foreign_reachable=$((foreign_reachable + 1))
        fi
    done

    # 判断网络环境
    if [ $domestic_reachable -ge 2 ]; then
        echo "检测到国内网络环境"
        return 0  # 国内环境
    elif [ $foreign_reachable -ge 2 ]; then
        echo "检测到国外网络环境"
        return 1  # 国外环境
    else
        echo "网络环境检测不确定（国内站点: $domestic_reachable, 国外站点: $foreign_reachable）"
        return 0  # 默认视为国内环境
    fi
}

# 配置国内源
configure_domestic_mirrors() {
    echo "配置国内源加速..."

    # 设置uv/pip镜像源
    export UV_INDEX_URL="https://pypi.tuna.tsinghua.edu.cn/simple/"
    export PIP_INDEX_URL="https://pypi.tuna.tsinghua.edu.cn/simple/"
    export PIP_TRUSTED_HOST="pypi.tuna.tsinghua.edu.cn"

    # 配置git国内镜像
    if git config --global --get url."https://github.com/".insteadOf >/dev/null; then
        echo "已存在git镜像配置，跳过"
    else
        git config --global url."https://gitee.com/mirrors/".insteadOf https://github.com/
        echo "已配置git镜像加速"
    fi
}

# 主菜单
main_menu() {
    clear
    echo "======================================"
    echo "        $SERVICE_NAME 管理工具         "
    echo "======================================"
    echo "[1] 安装服务"
    echo "[2] 卸载服务"
    echo "[3] 重载配置"
    echo "[4] 查看状态"
    echo "[5] 重启服务"
    echo "[0] 退出"
    echo "======================================"
    read -p "请选择操作 [0-5]: " -n 1 -r
    echo

    case $REPLY in
        1) install ;;
        2) uninstall ;;
        3) reload ;;
        4) status ;;
        5) restart ;;
        0) echo "退出程序"; exit 0 ;;
        *) echo "无效选择，请重试"; sleep 2; main_menu ;;
    esac
}

# 启动主菜单
main_menu